package cn.oi.klittle.era.widget.compat

import android.content.Context
import android.graphics.*
import android.os.Build
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import cn.oi.klittle.era.entity.widget.compat.KBubblesEntry
import cn.oi.klittle.era.entity.widget.compat.KGradientEntity
import cn.oi.klittle.era.utils.KScrimUtil
import org.jetbrains.anko.matchParent

//                FIXME 颜色渐变调用案例：

//                kview {
//                    //gradientColor(Color.GREEN)//fixme 系统背景色使用KScrimUtil柔和渐变
//                    gradient {
//                        //horizontalColors(Color.TRANSPARENT, Color.RED, Color.TRANSPARENT, Color.YELLOW)
//                        //verticalColors(Color.GREEN, Color.TRANSPARENT, Color.CYAN, Color.TRANSPARENT)
//                        left_color=Color.RED
//                        left_top_color=Color.GRAY
//                        right_bottom_color=Color.YELLOW
//                    }
//                    gradient_press{
//                        horizontalColors(Color.TRANSPARENT, Color.CYAN, Color.TRANSPARENT)
//                    }
//                }.lparams {
//                    width = matchParent
//                    height = kpx.x(300)
//                }

//    fixme 向上的阴影线。gravity = Gravity.BOTTOM 颜色从底部开始（向上）渐变。gravity = Gravity.LEFT 从左边开始渐变。
//    kview {
//        gradientColor(Color.parseColor("#33000000"), gravity = Gravity.BOTTOM)//fixme 第三方渐变工具。效果更好。
//    }.lparams {
//        width = matchParent
//        height = kpx.x(8)
//    }

/**
 * fixme 颜色渐变类
 */
open class K6GradientWidget : K6BubblesWidget {
    constructor(viewGroup: ViewGroup) : super(viewGroup.context) {
        viewGroup.addView(this)//直接添加进去,省去addView(view)
    }

    constructor(context: Context) : super(context) {}
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}


    //按下
    var gradient_press: KGradientEntity? = null

    fun gradient_press(block: KGradientEntity.() -> Unit): K6GradientWidget {
        if (gradient_press == null) {
            gradient_press = getMBubbles().copy()//整个属性全部复制过来。
        }
        block(gradient_press!!)
        invalidate()
        return this
    }

    //鼠标悬浮
    var gradient_hover: KGradientEntity? = null

    fun gradient_hover(block: KGradientEntity.() -> Unit): K6GradientWidget {
        if (gradient_hover == null) {
            gradient_hover = getMBubbles().copy()//整个属性全部复制过来。
        }
        block(gradient_hover!!)
        invalidate()
        return this
    }

    //聚焦
    var gradient_focuse: KGradientEntity? = null

    fun gradient_focuse(block: KGradientEntity.() -> Unit): K6GradientWidget {
        if (gradient_focuse == null) {
            gradient_focuse = getMBubbles().copy()//整个属性全部复制过来。
        }
        block(gradient_focuse!!)
        invalidate()
        return this
    }

    //选中
    var gradient_selected: KGradientEntity? = null

    fun gradient_selected(block: KGradientEntity.() -> Unit): K6GradientWidget {
        if (gradient_selected == null) {
            gradient_selected = getMBubbles().copy()//整个属性全部复制过来。
        }
        block(gradient_selected!!)
        invalidate()
        return this
    }

    //不可用
    var gradient_notEnable: KGradientEntity? = null

    fun gradient_notEnable(block: KGradientEntity.() -> Unit): K6GradientWidget {
        if (gradient_notEnable == null) {
            gradient_notEnable = getMBubbles().copy()//整个属性全部复制过来。
        }
        block(gradient_notEnable!!)
        invalidate()
        return this
    }

    //fixme 正常状态（先写正常样式，再写其他状态的样式，因为其他状态的样式初始值是复制正常状态的样式的。）
    var gradient: KGradientEntity? = null

    private fun getMBubbles(): KGradientEntity {
        if (gradient == null) {
            gradient = KGradientEntity()
        }
        return gradient!!
    }

    fun gradient(block: KGradientEntity.() -> Unit): K6GradientWidget {
        block(getMBubbles())
        invalidate()
        return this
    }

//    fixme 向上的阴影线。gravity = Gravity.BOTTOM 颜色从底部开始（向上）渐变。gravity = Gravity.LEFT 从左边开始渐变。
//    kview {
//        gradientColor(Color.parseColor("#33000000"), gravity = Gravity.BOTTOM)//fixme 第三方渐变工具。效果更好。
//    }.lparams {
//        width = matchParent
//        height = kpx.x(8)
//    }

    /**
     * fixme 使用KScrimUtil实现更柔和的颜色透明渐变;控件高度最好不要超过 height = kpx.x(40)(不然效果也不怎么好，高度太高，颜色分层明显。)
     * @param color 初始颜色值（最后会变成透明色）
     * @param numStops 渐变层数（越大，渐变色越柔和）
     * @param gravity 初始渐变方向;Gravity.TOP从上往下渐变；Gravity.BOTTOM 从下往上渐变;Gravity.LEFT 从左往右渐变。
     */
    open fun gradientColor(color: Int, numStops: Int = 8, gravity: Int = Gravity.TOP) {
        //要求版本号大于16
        if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN && color != null) {
            //fixme 系统背景色使用KScrimUtil柔和渐变
            setBackground(
                    KScrimUtil.makeCubicGradientScrimDrawable(
                            color, //顏色
                            numStops, //漸層數
                            gravity)); //起始方向
        }
    }

    open fun gradientColor(color: String, numStops: Int = 8, gravity: Int = Gravity.TOP) {
        gradientColor(Color.parseColor(color), numStops, gravity)
    }

    //fixme 绘制渐变色背景
    override fun draw2Bg(canvas: Canvas, paint: Paint) {
        super.draw2Bg(canvas, paint)
        drawGradient(canvas, paint, this)
    }

    private var gradientModel: KGradientEntity? = null
    private fun drawGradient(canvas: Canvas, paint: Paint, view: View) {
        view?.apply {
            if (gradient != null) {
                gradientModel = null
                if (isPressed && gradient_press != null) {
                    //按下
                    gradientModel = gradient_press
                } else if (isHovered && gradient_hover != null) {
                    //鼠标悬浮
                    gradientModel = gradient_hover
                } else if (isFocused && gradient_focuse != null) {
                    //聚焦
                    gradientModel = gradient_focuse
                } else if (isSelected && gradient_selected != null) {
                    //选中
                    gradientModel = gradient_selected
                }
                if (isEnabled == false && gradient_notEnable != null) {
                    //不可用
                    gradientModel = gradient_notEnable
                }
                //正常
                if (gradientModel == null) {
                    gradientModel = gradient
                }
                gradientModel?.let {
                    if (it.isDraw) {
                        paint.setShader(null)
                        it.apply {
                            paint.isAntiAlias = true
                            paint.isDither = true
                            paint.style = Paint.Style.FILL_AND_STROKE
                            //上半部分颜色
                            if (top_color != Color.TRANSPARENT) {
                                paint.color = top_color
                                canvas?.drawRect(RectF(0f + scrollX, 0f + scrollY, width.toFloat() + scrollX, height / 2f + scrollY), paint)
                            }

                            //下半部分颜色
                            if (bottom_color != Color.TRANSPARENT) {
                                paint.color = bottom_color
                                canvas?.drawRect(RectF(0f + scrollX, height / 2f + scrollY, width.toFloat() + scrollX, height.toFloat() + scrollY), paint)
                            }

                            //左半部分颜色
                            if (left_color != Color.TRANSPARENT) {
                                paint.color = left_color
                                canvas?.drawRect(RectF(0f + scrollX, 0f + scrollY, width.toFloat() / 2 + scrollX, height.toFloat() + scrollY), paint)
                            }

                            //右半部分颜色
                            if (right_color != Color.TRANSPARENT) {
                                paint.color = right_color
                                canvas?.drawRect(RectF(width / 2f + scrollX, 0f + scrollY, width.toFloat() + scrollX, height.toFloat() + scrollY), paint)
                            }

                            //左上角部分颜色
                            if (left_top_color != Color.TRANSPARENT) {
                                paint.color = left_top_color
                                canvas?.drawRect(RectF(0f + scrollX, 0f + scrollY, width.toFloat() / 2 + scrollX, height.toFloat() / 2 + scrollY), paint)
                            }

                            //右上角部分颜色
                            if (right_top_color != Color.TRANSPARENT) {
                                paint.color = right_top_color
                                canvas?.drawRect(RectF(width / 2f + scrollX, 0f + scrollY, width.toFloat() + scrollX, height.toFloat() / 2 + scrollY), paint)
                            }

                            //左下角部分颜色
                            if (left_bottom_color != Color.TRANSPARENT) {
                                paint.color = left_bottom_color
                                canvas?.drawRect(RectF(0f + scrollX, height / 2f + scrollY, width.toFloat() / 2 + scrollX, height.toFloat() + scrollY), paint)
                            }

                            //右下角部分颜色
                            if (right_bottom_color != Color.TRANSPARENT) {
                                paint.color = right_bottom_color
                                canvas?.drawRect(RectF(width / 2f + scrollX, height / 2f + scrollY, width.toFloat() + scrollX, height.toFloat() + scrollY), paint)
                            }

                            //水平渐变
                            horizontalColors?.let {
                                if (it.size > 1) {
                                    //fixme 渐变颜色数组必须大于等于2，不然异常
                                    var shader = LinearGradient(0f + scrollX, 0f + scrollY, width.toFloat() + scrollX, 0f + scrollY, it, null, Shader.TileMode.MIRROR)
                                    paint.setShader(shader)
                                } else if (it.size == 1) {
                                    paint.color = it[0]
                                }
                                canvas?.drawPaint(paint)
                            }

                            //fixme 水平渐变 和 垂直渐变 效果会叠加。垂直覆盖在水平的上面。

                            //垂直渐变
                            verticalColors?.let {
                                if (it.size > 1) {
                                    var shader = LinearGradient(0f + scrollX, 0f + scrollY, 0f + scrollX, height.toFloat() + scrollY, it, null, Shader.TileMode.MIRROR)
                                    paint.setShader(shader)
                                } else if (it.size == 1) {
                                    paint.color = it[0]
                                }
                                canvas?.drawPaint(paint)
                            }
                        }
                        paint.setShader(null)//防止其他地方受影响，所以渲染清空。
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        gradient = null
        gradient_focuse = null
        gradient_hover = null
        gradient_press = null
        gradient_selected = null
        gradient_notEnable = null
        gradientModel = null
    }

}